using System;
using System.IO.Ports;
using System.Collections.Concurrent; // ConcurrentDictionary需要
using System.Collections.Generic;
using System.Threading; // Thread需要
using System.Windows;   // Dispatcher需要

namespace StandardRobotppTool.Services
{
public class SerialPortService : IDisposable
{
    private readonly SerialPort _serialPort;
    private readonly Thread _readThread;
    private bool _isReading;

    // 公共属性用于数据绑定
    public string ReceivedData { get; private set; }

    public SerialPortService(string portName)
    {
        _serialPort = new SerialPort(portName)
        {
            BaudRate = 9600,
            Parity = Parity.None,
            StopBits = StopBits.One,
            DataBits = 8,
            Handshake = Handshake.None
        };

        _readThread = new Thread(ReadPort);
    }

    public void Start()
    {
        _serialPort.Open();
        _isReading = true;
        _readThread.Start();
    }

    private void ReadPort()
    {
        while (_isReading)
        {
            try
            {
                var data = _serialPort.ReadLine();
                UpdateData(data);
            }
            catch (TimeoutException) { /* 处理超时 */ }
        }
    }

    private void UpdateData(string data)
    {
        // 通过Dispatcher更新UI线程绑定的数据
        // Application.Current.Dispatcher.Invoke(() =>
        // {
        //     ReceivedData = data;
        //     DataPoints.Add(data);
        // });
    }

    public void SendData(string data)
    {
        if (_serialPort.IsOpen)
        {
            _serialPort.WriteLine(data);
        }
    }

    public void Dispose()
    {
        _isReading = false;
        _readThread.Join();
        _serialPort.Close();
    }
}
}